package com.xuyanhao.springbucksjpa;

import com.xuyanhao.springbucksjpa.model.Coffee;
import com.xuyanhao.springbucksjpa.model.CoffeeOrder;
import com.xuyanhao.springbucksjpa.model.OrderState;
import com.xuyanhao.springbucksjpa.repository.CoffeeRepository;
import com.xuyanhao.springbucksjpa.service.CoffeeOrderService;
import com.xuyanhao.springbucksjpa.service.CoffeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.util.Optional;

@SpringBootApplication
@Slf4j
@EnableTransactionManagement
@EnableJpaRepositories
public class SpringbucksJpaApplication implements ApplicationRunner {
  @Autowired private CoffeeRepository coffeeRepository;
  @Autowired private CoffeeService coffeeService;
  @Autowired private CoffeeOrderService coffeeOrderService;

  public static void main(String[] args) {
    SpringApplication.run(SpringbucksJpaApplication.class, args);
  }

  @Override
  public void run(ApplicationArguments args) throws Exception {
    log.info("All coffee: {}", coffeeRepository.findAll());
    Optional<Coffee> latte = coffeeService.findOneCoffee("Latte");
    if (latte.isPresent()) {
      CoffeeOrder order = coffeeOrderService.createOrder("Li Lei", latte.get());
      log.info("Update INIT to PAID: {}", coffeeOrderService.updateState(order, OrderState.PAID));
      log.info("Update PAID to INIT: {}", coffeeOrderService.updateState(order, OrderState.INIT));
    }
  }
}
